package com.analysis.service;

import com.analysis.dto.PageResponse;
import com.analysis.dto.QuestionPageRequest;
import com.analysis.entity.Project;
import com.analysis.entity.ProjectBrand;
import com.analysis.entity.Question;
import com.analysis.mapper.QuestionMapper;
import com.analysis.utils.QuestionExcelExportUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;

/**
 * 问题服务类
 */
@Service
@Transactional
public class QuestionService {

    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private ProjectBrandService projectBrandService;

    /**
     * 创建问题
     */
    public int createQuestion(Question question) {
        if (question.getProjectId() == null || StringUtils.isBlank(question.getQuestion())) {
            throw new IllegalArgumentException("缺少参数");
        }
        // 根据product_name和question去重
        Question existingQuestion = questionMapper.selectByProductNameAndQuestion(
                question.getProductName(),
                question.getQuestion(),
                question.getProjectId()
        );
        if (existingQuestion != null) {
            // 如果已存在相同的问题，返回0表示未创建新记录
            return 0;
        }
        return questionMapper.insert(question);
    }

    /**
     * 批量新增
     */
    public void batchAddQuestion(Project project, List<String> questions) {
        if (project.getId() == null || questions == null || questions.isEmpty()) {
            throw new IllegalArgumentException("缺少参数");
        }

        ProjectBrand brand = projectBrandService.selectByProjectId(project.getId());

        for (String question : questions) {
            // 根据product_name和question去重
            Question existingQuestion = questionMapper.selectByProductNameAndQuestion(
                    brand.getProductName(),
                    question,
                    project.getId()
            );
            if (existingQuestion == null) {
                Question questionEntity = new Question();
                questionEntity.setQuestion(question);
                questionEntity.setCompanyId(project.getCompanyId());
                questionEntity.setProjectId(project.getId());
                questionEntity.setProductName(brand.getProductName());
                questionMapper.insert(questionEntity);
            }
        }
    }

    /**
     * 根据ID删除问题（逻辑删除）
     */
    public int deleteQuestion(Long id) {
        return questionMapper.logicalDeleteById(id);
    }

    /**
     * 更新问题信息
     */
    public int updateQuestion(Question question) {
        return questionMapper.update(question);
    }

    /**
     * 根据ID查询问题
     */
    public Question getQuestionById(Long id) {
        return questionMapper.selectById(id);
    }

    /**
     * 根据项目ID查询问题列表
     */
    public List<Question> getQuestionsByProjectId(Long projectId) {
        return questionMapper.selectByProjectId(projectId);
    }

    /**
     * 根据品牌名称查询问题列表
     */
    public List<Question> getQuestionsByProductName(String productName) {
        return questionMapper.selectByProductName(productName);
    }

    /**
     * 根据问题内容模糊查询
     */
    public List<Question> getQuestionsByQuestionLike(String question) {
        return questionMapper.selectByQuestionLike(question);
    }

    /**
     * 查询所有问题
     */
    public List<Question> getAllQuestions() {
        return questionMapper.selectAll();
    }

    /**
     * 分页查询问题
     */
    public List<Question> getQuestionsByPage(int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        return questionMapper.selectByPage(offset, pageSize);
    }

    /**
     * 根据项目ID查询所有不重复的品牌名称
     */
    public List<String> getDistinctProductNamesByProjectId(Long projectId) {
        return questionMapper.selectDistinctProductNamesByProjectId(projectId);
    }

    /**
     * 统计问题总数
     */
    public int countQuestions() {
        return questionMapper.countAll();
    }

    /**
     * 根据条件查询问题
     */
    public List<Question> getQuestionsByCondition(Long projectId, String productName, String question, Integer enableStatus) {
        return questionMapper.selectByCondition(projectId, productName, question, enableStatus);
    }

    /**
     * 根据品牌名称和问题查询
     */
    public List<Question> getQuestionsByProductAndQuestion(String productName, String question, Long projectId) {
        return questionMapper.selectByProductAndQuestion(productName, question, projectId);
    }

    /**
     * 批量创建问题
     */
    public int batchCreateQuestions(List<Question> questions) {
        int count = 0;
        for (Question question : questions) {
            if (question.getEnableStatus() == null) {
                question.setEnableStatus(1);
            }
            // 根据product_name和question去重
            Question existingQuestion = questionMapper.selectByProductNameAndQuestion(
                    question.getProductName(),
                    question.getQuestion(),
                    question.getProjectId()
            );
            if (existingQuestion == null) {
                count += questionMapper.insert(question);
            }
        }
        return count;
    }

    /**
     * 根据项目ID统计问题数量
     */
    public int countQuestionsByProjectId(Long projectId) {
        return questionMapper.countByPageWithConditions(projectId, null, null, null);
    }

    /**
     * 根据品牌名称统计问题数量
     */
    public int countQuestionsByProductName(String productName) {
        return questionMapper.countByPageWithConditions(null, productName, null, null);
    }

    /**
     * 多条件分页查询问题
     */
    public PageResponse<Question> getQuestionsByPageWithConditions(QuestionPageRequest request) {
        int offset = (request.getPageNum() - 1) * request.getPageSize();

        List<Question> questions = questionMapper.selectByPageWithConditions(
                request.getProjectId(),
                request.getProductName(),
                request.getQuestion(),
                request.getCompetitorName(),
                offset,
                request.getPageSize()
        );

        int total = questionMapper.countByPageWithConditions(
                request.getProjectId(),
                request.getProductName(),
                request.getQuestion(),
                request.getCompetitorName()
        );

        return new PageResponse<>(questions, total, request.getPageNum(), request.getPageSize());
    }

    /**
     * 导出Question数据到Excel
     *
     * @param request 查询请求参数
     * @return Excel文件的字节数组
     * @throws IOException IO异常
     */
    public byte[] exportQuestionsToExcel(QuestionPageRequest request) throws IOException {
        // 查询数据
        List<Question> questions = questionMapper.selectByPageWithConditions(
                request.getProjectId(),
                request.getProductName(),
                request.getQuestion(),
                request.getCompetitorName(),
                0,
                Integer.MAX_VALUE
        );

        // 生成工作表名称
        String sheetName = generateSheetName(request);

        // 导出到Excel
        return QuestionExcelExportUtils.exportQuestionsToExcel(questions, sheetName);
    }

    /**
     * 生成工作表名称
     *
     * @param request 查询请求参数
     * @return 工作表名称
     */
    private String generateSheetName(QuestionPageRequest request) {
        StringBuilder sheetName = new StringBuilder("问题数据");

        if (request.getProductName() != null && !request.getProductName().trim().isEmpty()) {
            sheetName.append("_").append(request.getProductName());
        }

        if (request.getQuestion() != null && !request.getQuestion().trim().isEmpty()) {
            sheetName.append("_").append(request.getQuestion().substring(0, Math.min(10, request.getQuestion().length())));
        }

        return sheetName.toString();
    }
}
